package com.jiyi.adapter.recyclerview.base;


import android.annotation.SuppressLint;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.Paint;
import android.graphics.Typeface;
import android.graphics.drawable.Drawable;
import android.os.Build;
import android.support.v7.widget.RecyclerView;
import android.text.Spannable;
import android.text.SpannableString;
import android.text.util.Linkify;
import android.util.SparseArray;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.animation.AlphaAnimation;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.Checkable;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.ProgressBar;
import android.widget.RatingBar;
import android.widget.TextView;
import android.widget.TextView.BufferType;

import com.hyphenate.easeui.utils.EaseSmileUtils;
import com.jiyi.activity.new_maintenance.DetectSystemActivity;
import com.jiyi.adapter.ChildBuildAdapter;
import com.jiyi.adapter.ChildEquipAdapter;
import com.jiyi.adapter.ChildEscapeBuildAdapter;
import com.jiyi.adapter.DetectAdapter;
import com.jiyi.adapter.MalfunctionAdapter;
import com.jiyi.adapter.NewErrorTaskAdapter;
import com.jiyi.adapter.RepairProgressAdapter;
import com.jiyi.adapter.RepairTaskAdapter;
import com.jiyi.adapter.TempReportAdapter;
import com.jiyi.bean.maintenance.DetectCate;
import com.jiyi.bean.maintenance.NewErrorBean;
import com.jiyi.bean.maintenance.RepairProgressBean;
import com.jiyi.bean.maintenance.RepairTask;
import com.jiyi.bean.owner.FloorBean;
import com.jiyi.bean.zone.Topic;
import com.jiyi.widget.picselect.PicsAdapter;
import com.jiyi.widget.picshow.ImagePagerActivity;
import com.swift.maintenance.base.AppConfig;
import com.swift.maintenance.utils.FangWeiBoUtil;
import com.swift.utils.DeviceUtil;
import com.swift.utils.GlideUtil;

import java.util.List;

public class ViewHolder extends RecyclerView.ViewHolder
{
    private SparseArray<View> mViews;
    private View mConvertView;
    private Context mContext;

    public ViewHolder(Context context, View itemView)
    {
        super(itemView);
        mContext = context;
        mConvertView = itemView;
        mViews = new SparseArray<View>();
    }


    public static ViewHolder createViewHolder(Context context, View itemView)
    {
        ViewHolder holder = new ViewHolder(context, itemView);
        return holder;
    }

    public static ViewHolder createViewHolder(Context context,
                                              ViewGroup parent, int layoutId)
    {
        View itemView = LayoutInflater.from(context).inflate(layoutId, parent,
                false);
        ViewHolder holder = new ViewHolder(context, itemView);
        return holder;
    }

    /**
     * 通过viewId获取控件
     *
     * @param viewId
     * @return
     */
    public <T extends View> T getView(int viewId)
    {
        View view = mViews.get(viewId);
        if (view == null)
        {
            view = mConvertView.findViewById(viewId);
            mViews.put(viewId, view);
        }
        return (T) view;
    }

    public View getConvertView()
    {
        return mConvertView;
    }




    /****以下为辅助方法*****/

    /**
     * 设置TextView的值
     *
     * @param viewId
     * @param text
     * @return
     */
    public ViewHolder setText(int viewId, String text)
    {
        TextView tv = getView(viewId);
        tv.setText(text);
        return this;
    }
    
    //设置话题的内容
    public ViewHolder setTopicText(int viewId, Topic bean)
    {
        TextView tv = getView(viewId);
        SpannableString spannableString = FangWeiBoUtil.getWeiBoContent(tv.getContext(), bean, tv);
        tv.setText(spannableString);
        return this;
    }
    
    //设置环信的内容
    public ViewHolder setEaseMobText(int viewId, String text)
    {
        TextView tv = getView(viewId);
        Spannable smiledText = EaseSmileUtils.getSmiledText(mContext, text);
        tv.setText(smiledText,BufferType.SPANNABLE);
        return this;
    }

    public ViewHolder setImageResource(int viewId, int resId)
    {
        ImageView view = getView(viewId);
        view.setImageResource(resId);
        return this;
    }

    public ViewHolder setImageBitmap(int viewId, Bitmap bitmap)
    {
        ImageView view = getView(viewId);
        view.setImageBitmap(bitmap);
        return this;
    }

    public ViewHolder setImageDrawable(int viewId, Drawable drawable)
    {
        ImageView view = getView(viewId);
        view.setImageDrawable(drawable);
        return this;
    }

    public ViewHolder setBackgroundColor(int viewId, int color)
    {
        View view = getView(viewId);
        view.setBackgroundColor(color);
        return this;
    }

    public ViewHolder setBackgroundRes(int viewId, int backgroundRes)
    {
        View view = getView(viewId);
        view.setBackgroundResource(backgroundRes);
        return this;
    }

    public ViewHolder setTextColor(int viewId, int textColor)
    {
        TextView view = getView(viewId);
        view.setTextColor(textColor);
        return this;
    }

    public ViewHolder setTextColorRes(int viewId, int textColorRes)
    {
        TextView view = getView(viewId);
        view.setTextColor(mContext.getResources().getColor(textColorRes));
        return this;
    }

    @SuppressLint("NewApi")
    public ViewHolder setAlpha(int viewId, float value)
    {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB)
        {
            getView(viewId).setAlpha(value);
        } else
        {
            // Pre-honeycomb hack to set Alpha value
            AlphaAnimation alpha = new AlphaAnimation(value, value);
            alpha.setDuration(0);
            alpha.setFillAfter(true);
            getView(viewId).startAnimation(alpha);
        }
        return this;
    }

    public ViewHolder setVisible(int viewId, boolean visible)
    {
        View view = getView(viewId);
        view.setVisibility(visible ? View.VISIBLE : View.GONE);
        return this;
    }
    
    public ViewHolder setEnable(int viewId, boolean isEnable)
    {
        View view = getView(viewId);
        view.setEnabled(isEnable);
        return this;
    }

    public ViewHolder linkify(int viewId)
    {
        TextView view = getView(viewId);
        Linkify.addLinks(view, Linkify.ALL);
        return this;
    }

    public ViewHolder setTypeface(Typeface typeface, int... viewIds)
    {
        for (int viewId : viewIds)
        {
            TextView view = getView(viewId);
            view.setTypeface(typeface);
            view.setPaintFlags(view.getPaintFlags() | Paint.SUBPIXEL_TEXT_FLAG);
        }
        return this;
    }

    public ViewHolder setProgress(int viewId, int progress)
    {
        ProgressBar view = getView(viewId);
        view.setProgress(progress);
        return this;
    }

    public ViewHolder setProgress(int viewId, int progress, int max)
    {
        ProgressBar view = getView(viewId);
        view.setMax(max);
        view.setProgress(progress);
        return this;
    }

    public ViewHolder setMax(int viewId, int max)
    {
        ProgressBar view = getView(viewId);
        view.setMax(max);
        return this;
    }

    public ViewHolder setRating(int viewId, float rating)
    {
        RatingBar view = getView(viewId);
        view.setRating(rating);
        return this;
    }

    public ViewHolder setRating(int viewId, float rating, int max)
    {
        RatingBar view = getView(viewId);
        view.setMax(max);
        view.setRating(rating);
        return this;
    }

    public ViewHolder setTag(int viewId, Object tag)
    {
        View view = getView(viewId);
        view.setTag(tag);
        return this;
    }

    public ViewHolder setTag(int viewId, int key, Object tag)
    {
        View view = getView(viewId);
        view.setTag(key, tag);
        return this;
    }

    public ViewHolder setChecked(int viewId, boolean checked)
    {
        Checkable view = (Checkable) getView(viewId);
        view.setChecked(checked);
        return this;
    }

    /**
     * 关于事件的
     */
    public ViewHolder setOnClickListener(int viewId,
                                         View.OnClickListener listener)
    {
        View view = getView(viewId);
        view.setOnClickListener(listener);
        return this;
    }

    public ViewHolder setOnTouchListener(int viewId,
                                         View.OnTouchListener listener)
    {
        View view = getView(viewId);
        view.setOnTouchListener(listener);
        return this;
    }

    public ViewHolder setOnLongClickListener(int viewId,
                                             View.OnLongClickListener listener)
    {
        View view = getView(viewId);
        view.setOnLongClickListener(listener);
        return this;
    }

    public ViewHolder setImage(int viewId, Object tag) {
		ImageView view = getView(viewId);
		GlideUtil.load(view.getContext(), tag.toString(), view);
		return this;
	}
    
    public ViewHolder setAdapter(int viewId, Object tag) {
		GridView picGridView  = getView(viewId);
		//图片列表
		 List<String> picList = (List<String>) tag;
		 if (picList != null) {
			 final String [] urls = new String [picList.size()];
				for (int i = 0; i < picList.size(); i++) {
					urls[i] = picList.get(i);
				}
			 
				picGridView.setOnItemClickListener(new OnItemClickListener() {

				@Override
				public void onItemClick(AdapterView<?> parent, View view,
						int position, long id) {
					Intent intent = new Intent(view.getContext(),ImagePagerActivity.class);
					intent.putExtra(ImagePagerActivity.EXTRA_IMAGE_URLS, urls);
					intent.putExtra(ImagePagerActivity.EXTRA_IMAGE_INDEX, position);
					view.getContext().startActivity(intent);
				}
			});
			PicsAdapter picsAdapter = new PicsAdapter(picGridView.getContext(),picList);
			picGridView.setAdapter(picsAdapter);
		}
		return this;
	}
    
    //设置检测内容项的适配器
    public ViewHolder setDetectAdapter(int viewId, Object tag,final String company_id,final int parentPosition,final int type) {
		GridView gridView  = getView(viewId);
		final List<DetectCate> temp = (List<DetectCate>) tag;
		DetectAdapter mDetectAdapter = new DetectAdapter(gridView.getContext(), temp);
		gridView.setAdapter(mDetectAdapter);
		gridView.setOnItemClickListener(new OnItemClickListener() {

			@Override
			public void onItemClick(AdapterView<?> parent, View view,
					int position, long id) {
				// TODO 跳转到具体的检测系统
				DetectCate detectCate = temp.get(position);
				Intent intent = new Intent(parent.getContext(),DetectSystemActivity.class);
				intent.putExtra("title", detectCate.getName());
				intent.putExtra("id", detectCate.getTask_inspection_id());
				intent.putExtra("parentPosition", parentPosition);
				intent.putExtra("type", type);
				intent.putExtra("childPosition", position);
				intent.putExtra("code", detectCate.getCode());
				intent.putExtra(AppConfig.COMPANY_ID_KEY, company_id);
				parent.getContext().startActivity(intent);
			}
		});
		setDetectGridViewHeight(gridView);
		return this;
	}
    
    public ViewHolder setTextDraw(int viewId, int drawId,String text)
    {
    	TextView view = getView(viewId);
    	Drawable searchDraw = view.getContext().getResources()
				.getDrawable(drawId);
		searchDraw.setBounds(0, 0, searchDraw.getMinimumWidth(),
				searchDraw.getMinimumHeight());
		view.setCompoundDrawables(searchDraw, null, null, null);
		view.setText(text);
		return this;
    }
    
    /**   
     * @author: HYM 
     * @Title: setDetectGridViewHeight   
     * @Description: TODO(设置待检测的项目内容高度)   
     * @param gridview void 
     * @date: 2017-8-29
     */  
    public void setDetectGridViewHeight(GridView gridview) {  
        // 获取gridview的adapter  
        ListAdapter listAdapter = gridview.getAdapter();  
        if (listAdapter == null) {  
            return;  
        }  
        // 固定列宽，有多少列  
        int numColumns= 3; 
        int totalHeight = 0;  
        // 计算每一列的高度之和 
        for (int i = 0; i < listAdapter.getCount(); i += numColumns) {  
            // 获取gridview的每一个item  
            View listItem = listAdapter.getView(i, null, gridview); 
            listItem.measure(0, 0);  
            // 获取item的高度和  加上verticalSpacing的距离
            totalHeight += listItem.getMeasuredHeight()+DeviceUtil.dip2px(gridview.getContext(), 20);  
        }   
        
        //判断是否超过我们希望的高度，如果是就强制设置其高度为固定
        if (totalHeight > DeviceUtil.dip2px(gridview.getContext(), 250)) {
        	totalHeight = DeviceUtil.dip2px(gridview.getContext(), 250);
		}
        
        // 获取gridview的布局参数  
        ViewGroup.LayoutParams params = gridview.getLayoutParams();  
        params.height = totalHeight;  
        gridview.setLayoutParams(params);  
    }
    
    public void setTempReportAdapter(int viewId, List<RepairTask.RepairTaskItem> datas, int type , int position) {
		ListView listView = getView(viewId);
		TempReportAdapter tempReportAdapter = new TempReportAdapter(listView.getContext(), datas,type,position);
		listView.setAdapter(tempReportAdapter);
	}

	public void setMalfunctionAdapter(int viewId, List<RepairTask.RepairTaskItem> datas, int type , int position) {
		ListView listView = getView(viewId);
		MalfunctionAdapter malfunctionAdapter = new MalfunctionAdapter(listView.getContext(), datas,type,position);
		listView.setAdapter(malfunctionAdapter);
	}
//
//	public void setErrorTaskAdapter(int viewId,List<ErrorTaskItem> datas,int type ,int position) {
//		ListView listView = getView(viewId);
//		ErrorTaskAdapter errorTaskAdapter = new ErrorTaskAdapter(listView.getContext(), datas,type,position);
//		listView.setAdapter(errorTaskAdapter);
//	}

	public void setNewErrorTaskAdapter(int viewId, List<NewErrorBean.NewErrorItemBean> datas, int type , int position) {
		ListView listView = getView(viewId);
		NewErrorTaskAdapter errorTaskAdapter = new NewErrorTaskAdapter(listView.getContext(), datas,type,position);
		listView.setAdapter(errorTaskAdapter);
	}

	public void setRepairTaskAdapter(int viewId,List<com.jiyi.bean.maintenance.MantenanceRepairBean.RepairTaskItem> datas,int type ,int position) {
		ListView listView = getView(viewId);
		RepairTaskAdapter repairTaskAdapter = new RepairTaskAdapter(listView.getContext(), datas,type,position);
		listView.setAdapter(repairTaskAdapter);
	}

	public void setRepairProgressAdapter(int viewId, List<RepairProgressBean> datas, int type , int position) {
		ListView listView = getView(viewId);
		RepairProgressAdapter repairProgressAdapter = new RepairProgressAdapter(listView.getContext(), datas,type,position);
		listView.setAdapter(repairProgressAdapter);
	}

	public void setChildEquipAdapter(int viewId,List<FloorBean> datas) {
		ListView listView = getView(viewId);
		ChildEquipAdapter childEquipAdapter = new ChildEquipAdapter(listView.getContext(), datas);
		listView.setAdapter(childEquipAdapter);
	}

	public void setChildBuildAdapter(int viewId,List<FloorBean> datas) {
		ListView listView = getView(viewId);
		ChildBuildAdapter childBuildAdapter = new ChildBuildAdapter(listView.getContext(), datas);
		listView.setAdapter(childBuildAdapter);
	}

	public void setChildEscapeBuildAdapter(int viewId,List<FloorBean> datas) {
		ListView listView = getView(viewId);
		ChildEscapeBuildAdapter childBuildAdapter = new ChildEscapeBuildAdapter(listView.getContext(), datas);
		listView.setAdapter(childBuildAdapter);
	}
}
